package king.dominic.jcamera;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import java.io.File;

/**
 * Created by DominicKing on 2018/1/23.
 * OCameraPreview
 */

public class OCameraPreview extends FrameLayout implements ICameraView {
    private ICameraView mCameraView;
    private boolean isStart = false;

    public OCameraPreview(@NonNull Context context) {
        super(context);
    }

    public OCameraPreview(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public OCameraPreview(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public OCameraPreview(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mCameraView = new Camera2Preview(getContext());
//        } else {
        mCameraView = new CameraPreview(getContext());
//        }
        addView((View) mCameraView, 0);
    }

    public boolean isStart() {
        return isStart;
    }

    @Override
    @RequiresPermission(Manifest.permission.CAMERA)
    public void onResume(Activity activity) {
        if (isStart) return;
        if (mCameraView != null) mCameraView.onResume(activity);
        isStart = true;
    }

    @Override
    public void onPause() {
        isStart = false;
        if (mCameraView != null) {
            mCameraView.requestCurrentBitmap(null);
            mCameraView.onPause();
        }
    }

    @Override
    public void takePicture(File file) {
        if (mCameraView != null) mCameraView.takePicture(file);
    }

    @Override
    public void requestCurrentBitmap(CameraCallback callback) {
        if (mCameraView != null) mCameraView.requestCurrentBitmap(callback);
    }

    @Override
    public void openLight() {
        if (mCameraView != null)mCameraView.openLight();
    }

    @Override
    public void closeLight() {
        if (mCameraView != null)mCameraView.closeLight();
    }

    @Override
    public boolean isOpenLight() {
        return mCameraView != null && mCameraView.isOpenLight();
    }
}
